<template>
  <div class="regex-tester">
    <h2>正则表达式测试器</h2>
    <div class="input-group">
      <label for="pattern">正则表达式模式:</label>
      <input id="pattern" v-model="pattern" type="text" placeholder="例如：\d+">
    </div>
    <div class="input-group">
      <label for="flags">标志 (Flags):</label>
      <input id="flags" v-model="flags" type="text" placeholder="例如：g">
    </div>
    <div class="input-group">
      <label for="testText">测试文本:</label>
      <textarea id="testText" v-model="testText" rows="5" placeholder="输入测试文本"></textarea>
    </div>
    <button @click="runTest">测试</button>
    <p v-if="error" class="error">{{ error }}</p>
    <div v-if="matches.length > 0" class="result">
      <h3>匹配结果：</h3>
      <ul>
        <li v-for="(match, index) in matches" :key="index">
          <strong>匹配 {{ index + 1 }}:</strong> "{{ match.match }}" 在位置 [{{ match.index }}, {{ match.index + match.match.length - 1 }}]
        </li>
      </ul>
    </div>
    <div v-else-if="!error && testPerformed">
      <p>未匹配到结果。</p>
    </div>
  </div>
</template>

<script>
export default {
  name: "RegexTester",
  data() {
    return {
      pattern: "",
      flags: "",
      testText: "",
      matches: [],
      error: "",
      testPerformed: false
    };
  },
  methods: {
    runTest() {
      this.matches = [];
      this.error = "";
      this.testPerformed = false;
      if (!this.pattern) {
        this.error = "请填写正则表达式模式。";
        return;
      }
      try {
        const regex = new RegExp(this.pattern, this.flags);
        const results = [...this.testText.matchAll(regex)];
        results.forEach(result => {
          this.matches.push({
            match: result[0],
            index: result.index
          });
        });
      } catch (e) {
        this.error = "无效的正则表达式：" + e.message;
      }
      this.testPerformed = true;
    }
  }
};
</script>

<style scoped>
.regex-tester {
  max-width: 600px;
  margin: 20px auto;
  padding: 10px;
}
.input-group {
  margin: 10px 0;
}
.input-group label {
  display: block;
  margin-bottom: 5px;
}
.input-group input,
.input-group textarea {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
}
button {
  margin-top: 10px;
  padding: 8px 16px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
button:hover {
  background-color: #2980b9;
}
.error {
  color: red;
  margin-top: 10px;
}
.result {
  margin-top: 20px;
}
.result ul {
  list-style: none;
  padding: 0;
}
.result li {
  padding: 5px 0;
}
</style> 